$(function () {
    //动态渲染分类
    $.ajax({
        url: News.category_list,
        headers: { Authorization: localStorage.getItem('get_big_token') },
        success: function (res) {
            let html = template('itemizeTemp', res)
            $('.stauslist').html(html)
        }
    })

    //时间插件蓝色主题色
    jeDate("#postdate", {
        isinitVal: true,
        theme: { bgcolor: "#00A1CB", color: "#ffffff", pnColor: "#00CCFF" },
        format: "YYYY-MM-DD"
    });

    /* 2.js初始化选项 */
    tinymce.init({
        selector: '#itemcontent',
        height: '350px',
        language: 'zh_CN',
        directionality: 'ltl',
        browser_spellcheck: true,
        contextmenu: false,
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste imagetools wordcount",
            "code"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | code",
    });


    //获取编辑按钮过来的ID
    let id = location.search.split('=')[1]
    if (id) {
        //如果有ID就给输入框赋值并且修改标题与按钮名
        $('.common_title').text('文章编辑')
        $('.btn-release').text('修改')
        //为了类别下拉框的正常显示,故设置一个延时器
        setTimeout(() => {
            $.ajax({
                url: News.article_search,
                headers: { Authorization: localStorage.getItem('get_big_token') },
                data: { id },
                success: function (res) {
                    let dataId = res.data
                    $('#inputTitle').val(dataId.title)
                    $('.article_cover').prop('src', dataId.cover)
                    $('#postdate').val(dataId.date)
                    $('#categoryId').val(dataId.categoryId)
                    setTimeout(function () {
                        tinymce.activeEditor.setContent(dataId.content)
                    }, 100)
                }
            })
        }, 100);

    }

    //发布按钮的以及存为草稿点击事件
    $('.btnItems button').on('click', function () {
        if ($(this).text() == '存为草稿') {
            btnItem('草稿')
        } else {
            btnItem('已发布')
        }
    })


    //上传图片的改变事件处理
    $('#inputCover').on('change', function () {
        if ($('#inputCover')[0].files[0].type.indexOf('image') == -1) {
            alert('请上传图片作为封面')
            return
        }
        //1.2 获取用户选择的图片
        let file = $(this)[0].files[0]
        //1.3 将文件转为src路径
        let url = URL.createObjectURL(file);
        //1.4 将url路径赋值给img标签的src
        $('.article_cover').attr('src', url);
    })


    //将发布按钮和存为草稿的事件处理封装成函数重复调用
    var btnItem = function (state) {
        let content = tinymce.activeEditor.getContent()
        if (content.length == 0) {
            alert('请输入文章内容')
            return
        }

        let file = $('#inputCover')[0].files[0]
        //因编辑文章可不需要修改封面图片,故做一个安全判定
        if (!id || file) {
            if (!file || file.type.indexOf('image') == -1) {
                alert('请上传图片作为封面')
                console.log(123);
                return
            }
        }


        let formdata = new FormData($('#form')[0])
        formdata.append('state', state)
        formdata.set('content', content)

        //一个判断:如果有id那么就给url赋值
        if (id) {
            //给formdata赋值id
            formdata.append('id', id)
        }

        $.ajax({
            type: 'post',
            url: id ? News.article_edit : News.article_publish,
            headers: { Authorization: localStorage.getItem('get_big_token') },
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                alert(res.msg)
                location.href = './article_list.html'
            },
            error: function (err) {
                alert(err.responseJSON.msg)
            },
            dataType: 'json'
        })
    }

})